import { useLazyQuery, useMutation, useQuery } from "@apollo/client";
import {
  commitProduct_service,
  delProduct_service, getProductByOrgAndUser,
  getProductInfo_service,
  getProducts_service,
} from "../../graphql/product";
import { ProductType } from "../../pages/product/config";
import { message } from "antd";

export const useFetch_getProducts = (pageNum: number, pageSize: number) => {
  const {
    loading,
    refetch,
    data,
  }: {
    data: { getProducts: { data: ProductType[] } };
    loading: boolean;
    refetch: (options: any) => Promise<any>;
  } = useQuery(getProducts_service, {
    skip: true,
    variables: { page: { pageNum, pageSize } },
  });
  const formatData = (data: { getProducts: { data: ProductType[] } }) =>
    data?.getProducts.data.map((item, index: number) => ({
      ...item,
      key: index,
    }));
  // 第一个参数 params 查询表单和 params 参数的结合
  // 第一个参数中一定会有 pageSize 和  current ，这两个参数是 antd 的规范
  const handelRefetch = async (params: {
    pageSize?: number;
    current?: number;
    name?: string;
  }) => {
    // 这里需要返回一个 Promise,在返回之前你可以进行数据转化
    // 如果需要转化参数可以在这里进行修改
    const { data: msg, error } = await refetch({
      name: params.name,
      page: { pageNum: params?.current, pageSize: params?.pageSize },
    });
    return {
      data: formatData(msg),
      // success 请返回 true，
      // 不然 table 会停止解析数据，即使有数据
      success: !error,
      // 不传会使用 data 的长度，如果是分页一定要传
      total: (msg?.getProducts.page.total as number) ?? 0,
    };
  };
  return {
    getLoading: loading,
    refetch: handelRefetch,
    page: data?.getProducts.page as number,
    data: formatData(data) as ProductType[],
  };
};

export const useFetch_commitProduct = () => {
  const [edit, { loading }] = useMutation(commitProduct_service);

  const handleEdit = async (
    id: string,
    params: Partial<ProductType>,
    callback?: (isReload: boolean) => void
  ) => {
    const res = await edit({
      variables: {
        id,
        params,
      },
    });
    if (res.data) {
      void message.success(res.data?.commitProductInfo.message);
      // 刷新课程列表
      callback?.(true);
      return;
    }
    void message.error(res.data?.commitProductInfo.message);
  };

  return [handleEdit, loading];
};

export const useFetch_getProductInfo = () => {
  const [get, { loading }] = useLazyQuery(getProductInfo_service, {
    // 不使用缓存获取数据
    fetchPolicy: "network-only",
  });

  const getProductInfo = async (id: string) => {
    const data = await get({
      variables: {
        id,
      },
    });
    return data.data?.getProductInfo.data as ProductType;
  };
  return [getProductInfo, loading];
};

export const useFetch_delProduct = () => {
  const [del, { loading }] = useMutation(delProduct_service);

  const delProduct = async (id: string) => {
    const data = await del({
      variables: {
        id,
      },
    });
    return data.data.deleteProduct.message as string;
  };
  return [delProduct, loading];
};

export const useFetch_getProductsByOrgAndUser = () => {
  const [get, { loading }] = useLazyQuery(getProductByOrgAndUser, {
    // 不使用缓存获取数据
    fetchPolicy: "network-only",
  });

  const getProductsByOrgAndUser = async (orgId: string,userId: string) => {
    const data = await get({
      variables: {
        orgId,
        userId,
      },
    });
    return data.data?.getProductsByOrgAndUser.data as ProductType[];
  };
  return {getProductsByOrgAndUser, loading};
};
